//
//  StudentViewController.m
//  CoreDataTest
//
//  Created by wangrui on 14-2-28.
//  Copyright (c) 2014年 Ourui. All rights reserved.
//

#import "StudentViewController.h"
#import "Student.h"

@interface StudentViewController()<NSFetchedResultsControllerDelegate>{
    NSFetchedResultsController *_fechedResultContrller;
    NSManagedObjectContext *_mainObjectCtx;
}

@end

@implementation StudentViewController


- (void)viewDidLoad{
    [super viewDidLoad];
    
    
    UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addStudentInOtherThread:)];
    UIBarButtonItem *del = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(delStudent:)];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:add,del,nil];
}


- (void)delStudent:(id)sender{
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSArray *resluts = [self.mainObjectCtx executeFetchRequest:request error:nil];
    
    if (resluts.count>0) {
        [self.mainObjectCtx deleteObject:resluts.lastObject];
    }
    
    if ([self.mainObjectCtx hasChanges]) {
        [self.mainObjectCtx save:nil];
    }
}


#pragma mark - Multi Context

- (NSManagedObjectContext *)mainObjectCtx{
    if (!_mainObjectCtx) {
        NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
        ctx.persistentStoreCoordinator = self.coordinator;
        _mainObjectCtx = ctx;
    }
    
    return _mainObjectCtx;
}

- (void)addStudentInOtherThread:(id)sender{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"ctx creat:%@",[NSThread currentThread]);
        NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        ctx.parentContext = self.mainObjectCtx;
     
        //为了测试performBlock存储object的线程，新开一个线程
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"new:%@",[NSThread currentThread]);
            
            [ctx performBlock:^{
                NSLog(@"performBlock:%@",[NSThread currentThread]);
                NSEntityDescription *descroption = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:ctx];
                Student *t = [[Student alloc] initWithEntity:descroption insertIntoManagedObjectContext:ctx];
                t.num = [NSNumber numberWithInt:arc4random()%1000];
                t.name = [NSString stringWithFormat:@"name:%@",t.num];
                t.sex = @"男";
                
                NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
                request.predicate = [NSPredicate predicateWithFormat:@"num = %@",t.num];
                
                NSArray *resluts = [ctx executeFetchRequest:request error:nil];
                if (!(resluts.count>0)) {
                    [ctx insertObject:t];
                }
                
                if ([ctx hasChanges]) {
                    NSError *error;
                    if (![ctx save:&error]) {
                        NSLog(@"%@",error);
                        abort() ;
                    }
                }
            }];
            
            //要持久存储需要调用parentcontext的 Save
            [ctx.parentContext performBlock:^{
                [ctx.parentContext save:nil];
            }];
        });
    });
}




#pragma mark - UITableView DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.fechedResultContrller.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"studentCell" forIndexPath:indexPath];
    
    UILabel *numLabel = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:2];
    UILabel *sexLabel = (UILabel *)[cell.contentView viewWithTag:3];
    
    Student *stu = (Student *)[self.fechedResultContrller objectAtIndexPath:indexPath];
    numLabel.text = [stu.num stringValue];
    nameLabel.text = stu.name;
    sexLabel.text = stu.sex;
    
    return cell;
}

- (NSFetchedResultsController *)fechedResultContrller{
    if (!_fechedResultContrller) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
        NSSortDescriptor *des = [[NSSortDescriptor alloc]initWithKey:@"num" ascending:NO];
        [request setSortDescriptors:[NSArray arrayWithObjects:des,nil]];
        
        NSFetchedResultsController *fc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                             managedObjectContext:self.mainObjectCtx
                                                                               sectionNameKeyPath:nil
                                                                                        cacheName:nil];
        fc.delegate = self;
        [fc performFetch:nil];
        
        _fechedResultContrller = fc;
        
    }
    return _fechedResultContrller;
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView reloadData];
}

@end
